var BomMaterialFormModel = function (config, bomMaterial) {
  BaseModel.call(this);

  var fieldObjList = [{
    dataField: 'materialColorBomList',
    type: 'materialColor'
  }, {
    dataField: 'materialBomList',
    type: 'material'
  }, {
    dataField: 'subsidiaryBomList',
    type: 'subsidiary'
  }];

  var self = this;
  var fn = {
    initData: function (config, bomMaterial) {
      if (bomMaterial === undefined) {
        self.factoryNo = '';
        self.difficultLevelRate = 100;
        self.projectPicUrl = '';
        self.enclosurePicUrl = [];
        this.setCutSize();
        self.materialColorBomList = [];
        self.materialBomList = [];
        self.subsidiaryBomList = [];
        self.beatEdge = undefined;
        self.calMaterialList = [];

        self.materialCutData = {
          khhc: undefined,
          khhk: undefined,
          ztkd: undefined,
          ztcd: undefined,
          cutGap: undefined
        };
      } else {
        var masterData = bomMaterial.titleBean;
        self.id = masterData.id;
        self.factoryNo = masterData.factoryNo;
        self.enclosurePicUrl = [];

        var projectPicUrl = masterData.projectPicUrl;
        if (SysUtil.isEmpty(projectPicUrl)) {
          projectPicUrl = '';
        }
        self.projectPicUrl = projectPicUrl;

        difficultLevelRate = Number(masterData.difficultLevelRate);
        difficultLevelRate = _.round(difficultLevelRate * 100, 1);
        self.difficultLevelRate = difficultLevelRate;

        self.serialNo = masterData.serialNo;
        self.applyId = masterData.applyId;

        var calMaterialList = masterData.calJson;
        if (SysUtil.isEmpty(calMaterialList)) {
          calMaterialList = [];
        } else {
          calMaterialList = JSON.parse(calMaterialList);
        }
        self.calMaterialList = calMaterialList;

        this.setMaterialCutData(masterData);
        this.setCutSize(bomMaterial);
        this.setMaterialList(bomMaterial);
      }
      self.wasteRateList = [];
      this.setProjectConfig(config);
      self.setOldData(['factoryNo']);
    },

    setMaterialCutData: function (masterData) {
      var fields = ['khhc', 'khhk', 'ztcd', 'ztkd', 'cutGap'];
      var materialCutData = {};
      for (var i = 0; i < fields.length; i++) {
        var field = fields[i];
        var value = masterData[field];
        if (SysUtil.isEmpty(value)) {
          value = undefined;
        }
        materialCutData[field] = value;
      }
      self.materialCutData = materialCutData;
    },

    setCutSize: function (bomMaterial) {
      if (bomMaterial === undefined) {
        self.ringSize = '';
        self.legSize = '';
        return;
      }

      var ringSize = '',
        legSize = '';
      var materialList = bomMaterial.materialList;
      for (var i = 0; i < materialList.length; i++) {
        var material = materialList[i];
        if (material.bomType !== 4) {
          continue;
        }

        var materialType = material.materialType;
        if (materialType === '圈开料尺寸') {
          ringSize = material.materialModel;
        } else if (materialType === '肶开料尺寸') {
          legSize = material.materialModel;
        }
      }
      self.ringSize = ringSize;
      self.legSize = legSize;
    },

    setMaterialList: function (bomMaterial) {
      var materialList = bomMaterial.materialList;
      var materialColorBomList = [],
        materialBomList = [],
        subsidiaryBomList = [];

      for (var i = 0; i < materialList.length; i++) {
        var material = materialList[i];
        var bomType = material.bomType;
        if (bomType === 4) {
          continue;
        }
        material = this.formatMaterial(material);
        if (bomType === 1) {
          materialColorBomList.push(material);
        } else if (bomType === 2) {
          subsidiaryBomList.push(material);
        } else if (bomType === 3) {
          materialBomList.push(material);
        }
      }

      self.materialColorBomList = materialColorBomList;
      self.materialBomList = materialBomList;
      self.subsidiaryBomList = subsidiaryBomList;
    },

    formatMaterial: function (material) {
      var obj = {
        id: SysUtil.getId(),
        materialFeedTotalRate: Number(material.materialFeedTotalRate)
      };

      var bomType = material.bomType;
      if (bomType !== 2) {
        var materialDifficultLevelRate = Number(material.materialDifficultLevelRate);
        obj.materialKlfs = material.materialKlfs;
        obj.materialDifficultLevelRate = _.round(materialDifficultLevelRate * 100, 1);
        obj.materialMtlktTotal = Number(material.materialMtlktTotal);
      }
      if (bomType === 3) {
        obj.lineNo = undefined;
      } else if (bomType === 1) {
        obj.lineNo = material.lineNo;
        var beatEdge = material.beatEdge;
        if (SysUtil.isEmpty(beatEdge)) {
          beatEdge = undefined;
        }
        obj.beatEdge = beatEdge;
      }

      var defaultWarehouse = material.materialFactory;
      var materialTypeObj = {
        materialType: material.materialType,
        defaultWarehouse: Number(defaultWarehouse)
      };
      obj.materialType = materialTypeObj;

      var materialObj = {
        materialCode: material.materialCode,
        materialName: material.materialName,
        materialProviderName: material.materialProviderName,
        materialModel: material.materialModel,
        materialColor: material.materialColor,
        materialColorDescription: material.materialColorDescription
      };
      obj.materialObj = materialObj;

      var levelRankId = material.levelRankId;
      var classifyObj = '';
      if (!SysUtil.isEmpty(levelRankId)) {
        classifyObj = {
          levelRankId: levelRankId
        };
        var classifyLevel = BomMaterialFormModel.classifyLevel;
        for (var i = 0; i < classifyLevel.length; i++) {
          var field = classifyLevel[i];
          classifyObj[field] = material[field];
        }
      }
      obj.classifyObj = classifyObj;

      return obj;
    },

    setProjectConfig: function (config) {
      if (config === undefined) {
        self.projectConfig = {
          lengthDb: 0,
          widthDb: 0,
          lengthCut: 0,
          widthCut: 0
        };
        return;
      }

      var projectConfig = {};
      for (var key in config) {
        var value = config[key];
        value = Number(value);
        projectConfig[key] = value;
      }
      self.projectConfig = projectConfig;
    },

    checkMaterialValid: function (list, type) {
      var materialFields = ['materialType', 'materialObj'];
      if (type === 'subsidiary') {
        materialFields.push('materialFeedTotalRate');
      } else {
        materialFields.push('materialDifficultLevelRate', 'materialFeedTotalRate');
      }
      if (type === 'materialColor') {
        materialFields.unshift('lineNo');
      }
      for (var i = 0; i < list.length; i++) {
        var obj = list[i];
        for (var j = 0; j < materialFields.length; j++) {
          var field = materialFields[j];
          if (SysUtil.isEmpty(obj[field])) {
            return field;
          }
        }
      }
      return '';
    },

    getMaterialObject: function (material, type) {
      var postData = {};
      if (type === 'material') {
        postData.lineNo = -1;
      } else if (type === 'materialColor') {
        postData.lineNo = material.lineNo;
      }

      var fields = [];
      if (type === 'subsidiary') {
        fields = ['materialFeedTotalRate'];
      } else {
        fields = ['materialKlfs', 'materialMtlktTotal', 'materialFeedTotalRate'];
      }
      for (var i = 0; i < fields.length; i++) {
        var field = fields[i];
        var value = material[field];
        postData[field] = value;
      }

      var materialTypeObj = material.materialType;
      postData.materialType = materialTypeObj.materialType;
      postData.materialFactory = materialTypeObj.defaultWarehouse;
      var materialObj = material.materialObj;

      if (type !== 'subsidiary') {
        var materialDifficultLevelRate = material.materialDifficultLevelRate;
        materialDifficultLevelRate = _.round(materialDifficultLevelRate / 100, 3);
        postData.materialDifficultLevelRate = materialDifficultLevelRate;

        if (type === 'materialColor' && postData.materialType === '板材圈') {
          var arr = ModuleUtil.getSize(materialObj.materialModel);
          if (arr !== null) {
            var ylc = arr[0];
            var ylk = arr[1];
            var beatEdge = material.beatEdge;
            if (beatEdge === undefined) {
              beatEdge = 0;
            }

            postData.beatEdge = beatEdge;
            postData.ylc = ylc;
            postData.ylk = ylk;
          }
        }
      }

      materialObj = _.clone(materialObj);
      delete materialObj.materialCut;
      _.assignIn(postData, materialObj);

      var classifyObj = material.classifyObj;
      if (classifyObj !== '') {
        _.assignIn(postData, classifyObj);
      }

      var bomType = '';
      if (type === 'materialColor') {
        bomType = 1;
      } else if (type === 'material') {
        bomType = 3;
      } else {
        bomType = 2;
      }
      postData.bomType = bomType;

      return postData;
    },

    checkTableRowUpdate: function (list, beforeList) {
      var statusObj = {};
      var checkUpdateFields = ['lineNo', 'materialKlfs', 'materialDifficultLevelRate', 'materialMtlktTotal', 'materialFeedTotalRate',
        'beatEdge'];
      for (var i = 0; i < list.length; i++) {
        var obj = list[i];
        var beforeObj = beforeList[i];
        if (beforeObj === undefined) {
          statusObj[i] = true;
          continue;
        }

        if (obj.materialObj.materialCode !== beforeObj.materialObj.materialCode) {
          statusObj[i] = true;
          continue;
        }

        var updateFields = [];
        for (var j = 0; j < checkUpdateFields.length; j++) {
          var field = checkUpdateFields[j];
          var value = obj[field];
          var beforeValue = beforeObj[field];
          if (value !== beforeValue) {
            updateFields.push(field);
          }
        }

        var materialTypeObj = obj.materialType;
        var beforeMaterialTypeObj = beforeObj.materialType;
        if (materialTypeObj.materialType !== beforeMaterialTypeObj.materialType) {
          updateFields.push('materialType');
        }
        if (materialTypeObj.defaultWarehouse !== beforeMaterialTypeObj.defaultWarehouse) {
          updateFields.push('defaultWarehouse');
        }

        var classifyObj = obj.classifyObj;
        var beforeClassifyObj = beforeObj.classifyObj;
        if (classifyObj === '' || beforeClassifyObj === '') {
          if (classifyObj !== beforeClassifyObj) {
            updateFields.push('classifyObj');
          }
        } else {
          if (classifyObj.levelRankId !== beforeClassifyObj.levelRankId) {
            updateFields.push('classifyObj');
          }
        }
        statusObj[i] = updateFields;
      }
      return statusObj;
    },

    checkSameMaterialType: function (list) {
      if (list.length === 0) {
        return [];
      }
      var groupData = {};
      for (var i = 0; i < list.length; i++) {
        var obj = list[i];
        var lineNo = obj.lineNo;
        if (lineNo === '') {
          lineNo = -1;
        }
        var materialType = obj.materialType.materialType;
        var id = `${lineNo}_${materialType}`;
        var data = groupData[id];
        if (data === undefined) {
          data = [];
          groupData[id] = data;
        }
        data.push({
          lineNo: lineNo,
          rowNum: i + 1
        });
      }

      var sameList = [];
      for (var key in groupData) {
        var indexArray = groupData[key];
        if (indexArray.length > 1) {
          sameList.push(indexArray);
        }
      }
      return sameList;
    }
  };

  this.addMaterialData = function (type, ringMaterialTypeObj) {
    var list;
    var obj = {
      id: SysUtil.getId(),
      lineNo: undefined,
      materialType: '',
      materialObj: null,
      materialFeedTotalRate: undefined,
      classifyObj: ''
    };
    if (type === 'materialColor') {
      var materialColorBomList = this.materialColorBomList;
      var lineNo;
      if (materialColorBomList.length === 0) {
        lineNo = 1;
      } else {
        var material = materialColorBomList[materialColorBomList.length - 1];
        lineNo = material.lineNo;
        if (lineNo !== undefined) {
          lineNo++;
        }
      }

      list = materialColorBomList;
      obj.materialKlfs = '';
      obj.materialDifficultLevelRate = this.difficultLevelRate;
      obj.materialMtlktTotal = undefined;
      obj.lineNo = lineNo;
      if (ringMaterialTypeObj === null) {
        ringMaterialTypeObj = '';
      }
      obj.materialType = ringMaterialTypeObj;
    } else if (type === 'material') {
      list = this.materialBomList;
      obj.materialKlfs = '';
      obj.materialDifficultLevelRate = this.difficultLevelRate;
      obj.materialMtlktTotal = undefined;
    } else {
      list = this.subsidiaryBomList;
    }

    list.push(obj);
  };

  this.setCheckUpdate = function (beforeData) {
    var fields = ['factoryNo', 'ringSize', 'legSize', 'difficultLevelRate'];
    var updateStatusObj = {};
    for (var i = 0; i < fields.length; i++) {
      var field = fields[i];
      var value = this[field];
      var beforeValue = beforeData[field];
      updateStatusObj[field] = value !== beforeValue;
    }

    for (var i = 0; i < fieldObjList.length; i++) {
      var fieldObj = fieldObjList[i];
      var dataField = fieldObj.dataField;
      var list = this[dataField];
      var beforeList = beforeData[dataField];
      var statusObj = fn.checkTableRowUpdate(list, beforeList);
      updateStatusObj[dataField] = statusObj;
    }
    this.updateStatusObj = updateStatusObj;
  };

  this.checkUpdate = function (field, dataField, index) {
    var updateStatusObj = this.updateStatusObj;
    if (updateStatusObj === undefined) {
      return false;
    }

    if (dataField === undefined) {
      return updateStatusObj[field];
    }

    var statusArray = updateStatusObj[dataField];
    var statusFields = statusArray[index];
    if (statusFields === true) {
      return true;
    }

    return statusFields.indexOf(field) !== -1;
  };

  this.delMaterialData = function (materialData, type) {
    var list;
    if (type === 'materialColor') {
      list = this.materialColorBomList;
    } else if (type === 'material') {
      list = this.materialBomList;
    } else {
      list = this.subsidiaryBomList;
    }

    var index = _.findIndex(list, {
      id: materialData.id
    });
    list.splice(index, 1);
  };

  this.resetDifficultLevel = function () {
    var difficultLevelRate = this.difficultLevelRate;
    var materialColorBomList = this.materialColorBomList;
    for (var i = 0; i < materialColorBomList.length; i++) {
      var obj = materialColorBomList[i];
      obj.materialDifficultLevelRate = difficultLevelRate;
    }
    var materialBomList = this.materialBomList;
    for (var i = 0; i < materialBomList.length; i++) {
      var obj = materialBomList[i];
      obj.materialDifficultLevelRate = difficultLevelRate;
    }
  };

  this.setWasteRateList = function (wasteRateList) {
    wasteRateList = _.map(wasteRateList, function (obj) {
      var wasteRate = obj.wasteRate;
      return {
        id: obj.id,
        orderTotalEnd: obj.orderTotalEnd,
        orderTotalStart: obj.orderTotalStart,
        wasteRate: _.round(wasteRate * 100, 1),
        wasteTotal: obj.wasteTotal
      };
    });
    self.wasteRateList = wasteRateList;
  };

  this.checkValid = function () {
    var fields = ['factoryNo', 'difficultLevelRate'];
    for (var i = 0; i < fields.length; i++) {
      var field = fields[i];
      var value = this[field];
      if (SysUtil.isEmpty(value)) {
        return field;
      }
    }

    for (var i = 0; i < fieldObjList.length; i++) {
      var fieldObj = fieldObjList[i];
      var data = this[fieldObj.dataField];
      var type = fieldObj.type;
      var code = fn.checkMaterialValid(data, type);
      if (code !== '') {
        return {
          type: type,
          code: code
        };
      }
    }
    return '';
  };

  this.calCutMaterial = function (type, materialData) {
    if (type === undefined) {
      var value = ModuleUtil.calMaterialCutData(this, materialData);
      if (value !== null) {
        materialData.materialMtlktTotal = value;
        if (value !== undefined) {
          materialData.materialFeedTotalRate = _.round(1 / value, 3);
        } else {
          materialData.materialFeedTotalRate = undefined;
        }
      }
      return;
    }

    var size = this[type];
    size = ModuleUtil.getSize(size);
    if (size === null) {
      return;
    }

    for (var i = 0; i < fieldObjList.length; i++) {
      var fieldObj = fieldObjList[i];
      if (fieldObj.type === 'subsidiary') {
        continue;
      }
      var list = this[fieldObj.dataField];
      for (var j = 0; j < list.length; j++) {
        var obj = list[j];
        var value = ModuleUtil.calCutMaterial(obj, {
          size: size,
          type: type,
          projectConfig: this.projectConfig
        });
        if (value !== null) {
          obj.materialMtlktTotal = value;
          if (value !== undefined) {
            obj.materialFeedTotalRate = _.round(1 / value, 3);
          } else {
            obj.materialFeedTotalRate = undefined;
          }
        }
      }
    }
  };

  this.setEnclosurePicUrl = function (enclosurePicUrl) {
    enclosurePicUrl = _.filter(enclosurePicUrl, function (url) {
      return !SysUtil.isEmpty(url);
    });
    this.enclosurePicUrl = enclosurePicUrl;
    self.setOldData(['enclosurePicUrl']);
  };

  this.resetMaterialCutData = function () {
    var ringSize = this.ringSize;
    var arr = ModuleUtil.getSize(ringSize);
    var materialCutData = this.materialCutData;
    if (arr === null) {
      materialCutData.khhc = undefined;
      materialCutData.khhk = undefined;
    } else {
      materialCutData.khhc = arr[0];
      materialCutData.khhk = arr[1];
    }
  };

  this.hasMaterialColorObj = function (materialData) {
      var materialColorBomList = this.materialColorBomList;
      if (materialColorBomList.indexOf(materialData) !== -1) {
        return true;
      }
      return false;
    },

    this.checkSameMaterialType = function () {
      var codeArray = [];
      var materialList = this.materialColorBomList;
      var materialColorSameList = fn.checkSameMaterialType(materialList);
      if (materialColorSameList.length > 0) {
        codeArray.push('<div style="font-size:15px">颜色物料BOM:</div>');
        for (var i = 0; i < materialColorSameList.length; i++) {
          var materialColorSame = materialColorSameList[i];
          codeArray.push(`<div>序号为${materialColorSame[0].lineNo}的物料类型重复</div>`);
        }
      }

      var materialSameList = fn.checkSameMaterialType(this.materialBomList);
      if (materialSameList.length > 0) {
        codeArray.push('<div style="font-size:15px">物料BOM:</div>');
        for (var i = 0; i < materialSameList.length; i++) {
          var materialSame = materialSameList[i];
          materialSame = _.map(materialSame, 'rowNum');
          codeArray.push(`<div>第${materialSame.join('、')}行物料类型重复</div>`);
        }
      }

      return codeArray;
    };

  this.getObject = function (type, user) {
    var masterData = {
      status: -1,
      factoryNo: this.factoryNo,
      projectPicUrl: this.projectPicUrl
    };

    if (user) {
      masterData.creater = user.userName;
    }

    var id = this.id;
    if (type === 'update' && !SysUtil.isEmpty(id)) {
      masterData.id = id;
      masterData.serialNo = this.serialNo;
    }

    var difficultLevelRate = this.difficultLevelRate;
    difficultLevelRate = _.round(difficultLevelRate / 100, 3);
    masterData.difficultLevelRate = difficultLevelRate;

    var calMaterialList = this.calMaterialList;
    if (calMaterialList === undefined) {
      masterData.calJson = '';
    } else {
      masterData.calJson = JSON.stringify(calMaterialList);
    }

    var materialCutData = this.materialCutData;
    var fields = ['khhc', 'khhk', 'ztkd', 'ztcd', 'cutGap'];
    for (var i = 0; i < fields.length; i++) {
      var field = fields[i];
      var value = materialCutData[field];
      if (value !== undefined) {
        masterData[field] = value;
      }
    }

    var materialList = [];
    var subsidiaryIndex = 100;
    for (var i = 0; i < fieldObjList.length; i++) {
      var fieldObj = fieldObjList[i];
      var data = this[fieldObj.dataField];
      var type = fieldObj.type;
      for (var j = 0; j < data.length; j++) {
        var obj = data[j];
        var materialPostData = fn.getMaterialObject(obj, type);
        if (type === 'subsidiary') {
          materialPostData.lineNo = subsidiaryIndex;
          subsidiaryIndex++;
        }
        materialList.push(materialPostData);
      }
    }

    materialList.push({
      lineNo: -1,
      materialFactory: 3,
      materialType: '圈开料尺寸',
      materialModel: this.ringSize,
      bomType: 4
    }, {
      lineNo: -1,
      materialFactory: 3,
      materialType: '肶开料尺寸',
      materialModel: this.legSize,
      bomType: 4
    });

    var postData = {
      titleBean: masterData,
      materialList: materialList
    };
    return postData;
  };

  fn.initData(config, bomMaterial);
};

BomMaterialFormModel.tableCol = {
  materialColorBomCol: [{
    id: "materialName",
    label: "物料名称"
  }, {
    id: "materialModel",
    label: "物料规格"
  }, {
    id: "materialProviderName",
    label: "供应商"
  }, {
    id: "materialColor",
    label: "色号"
  }, {
    id: "materialColorDescription",
    label: "颜色描述"
  }, {
    id: "materialKlfs",
    label: "开料方式"
  }, {
    id: "materialMtlktTotal",
    label: "每条料可开数"
  }],
  materialBomCol: [{
    id: "materialName",
    label: "物料名称"
  }, {
    id: "materialModel",
    label: "物料规格"
  }, {
    id: "materialProviderName",
    label: "供应商"
  }, {
    id: "materialColor",
    label: "色号"
  }, {
    id: "materialColorDescription",
    label: "颜色描述"
  }, {
    id: "materialKlfs",
    label: "开料方式"
  }, {
    id: "materialMtlktTotal",
    label: "每条料可开数"
  }],
  subsidiaryBomCol: [{
    id: "materialName",
    label: "物料名称"
  }, {
    id: "materialModel",
    label: "物料规格"
  }, {
    id: "materialProviderName",
    label: "供应商"
  }, {
    id: "materialColor",
    label: "色号"
  }, {
    id: "materialColorDescription",
    label: "颜色描述"
  }]
};

BomMaterialFormModel.classifyLevel = [
  'levelRankOne',
  'levelRankTwo',
  'levelRankThree',
  'levelRankFour',
  'levelRankFive',
  'levelRankSix',
  'levelRankSeven',
  'levelRankEight',
  'levelRankNine',
  'levelRankTen'
];
